import Config from "@/config.js"; // 系统参数
import md5 from "@/static/js/md5.js";
import cookies from 'weapp-cookie'



/**网络请求 */
export function request(url, options) {
	return new Promise(function(resolve, reject) {
		options = options || {};
		options.data = options.data || {}

		if (options.data.interfaceName) {
			url = url + '/' + options.data.interfaceName;
		}

		var time = new Date().getTime();
		var str = Config.productId + time;

		if (options.data.param) {
			Object.keys(options.data.param).sort().map(key => {
				str += key + options.data.param[key];
			});
		} else if (options.data) {
			Object.keys(options.data).sort().map(key => {
				str += key + options.data[key];
			});
		}

		if (options.data.param) {
			options.data.param.t = time;
			options.data.param.sign = md5.hex_md5(encodeURIComponent(str));
		} else if (options.data) {
			options.data.t = time;
			options.data.sign = md5.hex_md5(encodeURIComponent(str));
		} else {
			console.log('加密出错');
		}

		var header = {
			Authorization: "Bearer " + uni.getStorageSync('Authorization'),
			projectId: uni.getStorageSync("projectId"),
			appId: Config.appId,
		};

		if (options['content-type']) {
			// console.log(options['content-type'])
			header['content-type'] = options['content-type']
		}

		let csrf_token = cookies.get('csrf-token', Config.service.domain);
		if (csrf_token) {
			header['csrf-token'] = csrf_token;
		}

		uni.request({
			url: url,
			method: options.method || 'post',
			dataType: options.data.dataType || 'json',
			data: options.data.param || options.data || {},
			header: header,
			success: function(res) {
				setTimeout(() => {
					if (res.data.code == '110') {
						uni.showModal({
							title: '提示',
							content: '无权限访问，请联系管理员',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}

							}
						});
					}
				}, 600)
				if (res.data.code == '1011008' || res.data.code == '1011004') {
					var Authorization = uni.getStorageSync('Authorization')
					if (Authorization && Authorization.length > 0) {
						uni.setStorageSync('Authorization',"")
						uni.reLaunch({
							url: '/pages/home/home'
						})
					
						
						// setTimeout(() => {
						// 	uni.showModal({
						// 		title: '提示',
						// 		content: res.data.message,
						// 		showCancel: false,
						// 		confirmText: '重新登录',
						// 		success: function(res) {
						// 			if (res.confirm) {
						// 				uni.reLaunch({
						// 					url: '/pages/home/home'
						// 				})
						// 				console.log('用户点击确定');
						// 			} else if (res.cancel) {
						// 				console.log('用户点击取消');
						// 			}
						// 		}
						// 	});
						// }, 500)
					}
				}
				resolve(res.data);
			},
			fail: function(res) {
				console.log("uni.request fail", res)
				reject(res);
			}
		});

	})
}
/**网络请求 */
export function uploadFile(url, options) {
	return new Promise(function(resolve, reject) {
		options = options || {};
		options.data = options.data || {}

		if (options.data.interfaceName) {
			url = url + '/' + options.data.interfaceName;
		}

		var time = new Date().getTime();
		var str = Config.productId + time;

		if (options.data.param) {
			Object.keys(options.data.param).sort().map(key => {
				str += key + options.data.param[key];
			});
		} else if (options.data) {
			Object.keys(options.data).sort().map(key => {
				str += key + options.data[key];
			});
		}

		if (options.data.param) {
			options.data.param.t = time;
			options.data.param.sign = md5.hex_md5(encodeURIComponent(str));
		} else if (options.data) {
			options.data.t = time;
			options.data.sign = md5.hex_md5(encodeURIComponent(str));
		} else {
			console.log('加密出错');
		}

		var header = {
			openId: uni.getStorageSync('openid'),
			appId: Config.appId,
			projectId: uni.getStorageSync("projectId"),
		};

		let csrf_token = cookies.get('csrf-token', Config.service.domain);
		if (csrf_token) {
			header['csrf-token'] = csrf_token;
		}

		uni.uploadFile({
			url: url,
			filePath: options.data.files, //chooseImage上传的图片
			name: 'file', //需要传给后台的图片字段名称
			formData: options.data.param || options.data || {},
			header: header,
			success(res) {
				resolve(JSON.parse(res.data));
			},
			fail: function(res) {
				console.log("uni.request fail", res)
				reject(res);
			}
		})
	})
}
export function uploadFiles(url, options) {
	if (options.data.interfaceName) {
		url = url + '/' + options.data.interfaceName;
	}
	let gUploadFilesPath = options.data.files;
	let gNewPaths = []
	let gSuccessUp = 0; //成功
	let gFailUp = 0; //失败
	let gCount = 0; //第几张
	let gLength = options.data.files.length; //总数


	function recursionUploading(imgPaths, newPaths, successUp, failUp, count, length, completed) {
		// console.log(imgPaths, newPaths,successUp, failUp, count, length,completed)
		wx.showLoading({
			title: count == 0 ? "正在上传..." : '正在上传第' + (count + 1) + '张',
		});
		var header = {
			Authorization: "Bearer " + uni.getStorageSync('Authorization'),
			// #ifndef H5
			'content-type': 'multipart/form-data',
			// #endif
		};
		console.log('url:', url)
		uni.uploadFile({
			url: url,
			filePath: imgPaths[count],
			formData: {
				indexImg: count
			},
			name: "file",
			header: header,
			success(e) {
				var res = JSON.parse(e.data)
				console.log("uploadFile success:", res)
				if (res.success) {
					successUp++; //成功+1
					newPaths.push(res.data)
				} else {
					failUp++; //失败+1
				}

			},
			fail(err) {
				console.log("uploadFile fail:", err)
				failUp++; //失败+1
			},
			complete(e) {
				count++; //下一张
				if (count >= length) {
					uni.showToast({
						title: '上传成功' + successUp + '张',
						icon: 'none'
					})
					console.log('上传成功' + successUp + '张')
					typeof completed == 'function' && completed();
				} else {
					//递归调用，上传下一张
					recursionUploading(imgPaths, newPaths, successUp, failUp, count, length, completed);
				}
			}
		})
	}



	// recursionUploading(uploadFilesPath , newPaths, successUp, failUp, count, length);//调用上传方法



	return new Promise(function(resolve, reject) {
		recursionUploading(gUploadFilesPath, gNewPaths, gSuccessUp, gFailUp, gCount, gLength, () => {
			if (gNewPaths&&gNewPaths.length>0){
				resolve({
					files: gNewPaths,
					success: true
				})
			}else{
				resolve({
					files: [],
					success: false
				})
			}
		}); //调用上传方法
	})
}